package com.iecas.handler;

import cn.hutool.core.util.StrUtil;
import com.iecas.entity.User;
import com.iecas.enums.BizEnum;
import com.iecas.enums.ResponseEnum;
import com.iecas.launch.Client;
import com.iecas.launch.Server;
import com.iecas.request.LoginReq;
import com.iecas.request.Root;
import com.iecas.response.BaseResponse;
import com.iecas.response.LoginResp;
import com.iecas.service.LoginService;
import com.iecas.utils.OnlineManager;

import java.nio.channels.SocketChannel;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

public class LoginReqHandler extends BaseHandler {
    LoginService loginService = new LoginService();

    @Override
    BaseResponse handle(Root baseRequest, Server server, Client client, SocketChannel socketChannel) {
        LoginResp loginResp = new LoginResp();
        loginResp.setCode(BizEnum.LOGIN_RESP.getCode());
        String userName = ((LoginReq) baseRequest).getUserName();
        String password = ((LoginReq) baseRequest).getPassword();
        // 看看是否登录了
//        Collection<User> users = OnlineManager.onlineUser.values();
//        Set<String> collect = users.stream().map(User::getUsername).collect(Collectors.toSet());
//        if (collect.contains(userName)) {
//            loginResp.setStatus(ResponseEnum.ERROR.getCode());
//            loginResp.setMsg("用户已登录");
//            return loginResp;
//        }
        // 登录
        String token = loginService.login(userName, password);
        if (StrUtil.isNotBlank(token)) {
            loginResp.setStatus(ResponseEnum.SUCCESS.getCode());
            loginResp.setToken(token);
        } else {
            loginResp.setStatus(ResponseEnum.ERROR.getCode());
            loginResp.setMsg("用户名密码错误");
        }
        return loginResp;

    }
}
